/* 科目管理 */
import React, { PureComponent } from 'react';
import {
  Tree,
  Row,
  Col,
  Input,
  InputNumber,
  Form,
  Button,
  Tabs,
  Spin,
  message,
  Cascader,
  Modal,
  Card,
  Radio
} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import Authorized from '../../components/Authorized/Authorized'
import { addSubject, getSubject, changeSubject, deleteSubject, checkSubjectTopic } from '../../services/lessons';
import {hasIsSw} from '@/utils/utils'
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};
class Index extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      rightLoading: false,
      currentNode: '',
      pid: '',
      title: '',
      num: null,
      level: '',
      treeData: [],
      options: [],
      addPid: '',
      addLevel: '',
      treeLoading: true,
      currentName: '',
      currentNum: '',
      currentLevel: '',
      currentPid: '',
      currentId: '',
      node: {},
      currentTab: '1',
      currentLevelEdit: '',
      currentLevelEditValue: [],
      is_sw:2,
      currentIs_sw:2
    };
  }
  renderType = () => {
    getSubject().then((res) => {
      if (!res || !res[0]) {
        return this.setState({
          treeLoading: false
        });
      };
      let data = JSON.stringify(res);
      let data2 = JSON.stringify(res);
      data = data.replace(/id/g, 'key').replace(/pkey/g, 'pid');
      data2 = data2
        .replace(/id/g, 'value')
        .replace(/title/g, 'label')
        .replace(/pvalue/g, 'pid');
      data2 = JSON.parse(data2)
      data2.unshift({ value: '', label: '顶级分类', level: 0, pid: 0, num: 0 })
      this.setState({
        treeData: JSON.parse(data),
        options: data2,
        treeLoading: false,
      });
    });
  };
  changeTabs = (e: any) => {
    this.setState({
      currentNode: '',
      pid: '',
      currentTab: e
    });
  };
  selectTreeNode = (e: any, node: any) => {
    const { title, key, level, num, pid,is_sw } = node.node;
    this.setState({
      currentNode: title,
      node,
      pid: key,
      level: level,
      currentName: title,
      currentNum: num,
      currentPid: pid,
      currentId: key,
      currentTab: '2',
      currentLevel: level,
      currentLevelEditValue: [],
      currentIs_sw:is_sw
    });
  };
  changeTitleAdd = (e: any) => {
    this.setState({
      title: e.target.value,
    });
  };
  changeNumAdd = (e: any) => {
    this.setState({
      num: e,
    });
  };
  submitAdd = () => {
    const { title, num, addPid, addLevel,is_sw } = this.state;
    addSubject({ title, num, pid: addPid || 0, level: addLevel ? addLevel + 1 : 1,is_sw }).then((res) => {
      if (res.status === 1) {
        this.renderType();
        message.success('添加成功');
      } else {
        message.error('添加失败');
      }
    });
  };
  selectChangeLevelAdd = (e: any, node: any) => {
    const currentnode = node[node.length - 1] || {};
    const { level, value } = currentnode;
    this.setState({
      addPid: value,
      addLevel: level,
    });
  };
  selectChangeLevelEdit = (e: any, node: any) => {
    const currentnode = node[node.length - 1] || { level: '', value: 0 };
    const { level, value } = currentnode;
    this.setState({
      currentPid: value,
      currentLevelEdit: level,
      currentLevelEditValue: e
    });
  };
  changeCurrentName = (e: any) => {
    this.setState({
      currentName: e.target.value,
    });
  };
  changeCurrentNum = (e: any) => {
    this.setState({
      currentNum: e,
    });
  };
  submitEdit = () => {
    const { currentLevel, currentName, currentPid, currentNum, currentId, currentLevelEdit,currentIs_sw } = this.state;
    if (currentPid === currentId) return message.error('操作失败')
    changeSubject({
      title: currentName,
      num: currentNum,
      pid: currentPid || 0,
      level: String(currentLevelEdit) ? currentLevelEdit + 1 : currentLevel,
      id: currentId,
      is_sw:currentIs_sw
    }).then((res) => {
      if (res.status === 1) {
        message.success('已更新')
        this.renderType()
      } else {
        message.error('更新失败')
      }
    });
  };
  deleteHandle = () => {
    const { currentId, node } = this.state;
    const deleteHandle = () => {
      let arr = [];
      for (let i = 0; i < node.node.children.length; i++) {
        const item = node.node.children[i];
        arr.push(item.key)
      }
      let str = [...arr, currentId].join(',')
      deleteSubject({ id: str }).then(res => {
        if (res.status === 1) {
          message.success('已删除')
          this.renderType()
        } else {
          message.error('删除失败')
        }
      });
    }

    checkSubjectTopic({ id: currentId }).then(res => {
      if (res[0]) {
        return Modal.info({
          title: '提示',
          content: '您所删除的分类下还有题库，请删除题库后进行删除',
        });
      }
      if (node.node.children[0]) {
        return Modal.confirm({
          title: '提示',
          content: '您要删除的分类下面有子分类，确定要全部删除吗？',
          onOk: () => {
            deleteHandle()
          },
        });
      }
      Modal.confirm({
        title: '提示',
        content: '确定删除该分类？',
        onOk: () => {
          deleteHandle()
        },
      });
    })

  };
  changeIsSw=(e:any)=>{
    this.setState({
      is_sw:e.target.value
    })
  }
  changeCurrentIsSw=(e:any)=>{
    this.setState({
      currentIs_sw:e.target.value
    })
  }
  componentDidMount() {
    this.renderType();
  }

  render() {
    const {
      rightLoading,
      currentNode,
      treeData,
      treeLoading,
      currentName,
      currentNum,
      options,
      currentId,
      currentTab,
      currentLevelEditValue,
      currentIs_sw
    } = this.state;
    return (
      <PageContainer>
        <Card>
          <Row gutter={30}>
            <Col span={8} style={{ borderRight: '1px solid #f0f0f0' }}>
              <Spin spinning={treeLoading}>
                <Tree treeData={treeData} onSelect={this.selectTreeNode} />
              </Spin>
            </Col>
            <Col span={16}>
              <Tabs onChange={this.changeTabs} activeKey={currentTab}>
                <Tabs.TabPane key="1" tab="添加">
                  <Form>
                    <Form.Item {...layout} label="上级">
                      <Cascader
                        options={options}
                        onChange={this.selectChangeLevelAdd}
                        changeOnSelect
                        style={{ width: 300 }}
                        placeholder="请选择上级"
                      />
                    </Form.Item>
                    <Form.Item {...layout} label="名称">
                      <Input
                        style={{ width: 300 }}
                        placeholder="请输入科目名称"
                        onChange={this.changeTitleAdd}
                      />
                    </Form.Item>
                    {
                      hasIsSw()&&  <Form.Item {...layout} label="类别">
                      <Radio.Group onChange={this.changeIsSw} defaultValue={2}>
                        <Radio value={2}>特种设备</Radio>
                        <Radio value={1}>特种作业</Radio>
                      </Radio.Group>
                    </Form.Item>
                    }
                  
                    <Form.Item label="排序" {...layout}>
                      <InputNumber
                        style={{ width: 300 }}
                        placeholder="请输入科目排序"
                        onChange={this.changeNumAdd}
                      />
                    </Form.Item>
                    <Form.Item {...tailLayout}>
                      <Authorized authority={[202]}>
                        <Button type="primary" onClick={this.submitAdd}>
                          提交
                    </Button>
                      </Authorized>

                    </Form.Item>
                  </Form>
                </Tabs.TabPane>
                {currentId && (
                  <React.Fragment>
                    <Tabs.TabPane key="2" tab="修改">
                      <Spin spinning={rightLoading}>
                        <Form>
                          <Form.Item {...layout} label="上级">
                            <Cascader
                              options={options}
                              value={currentLevelEditValue}
                              onChange={this.selectChangeLevelEdit}
                              changeOnSelect
                              style={{ width: 300 }}
                            />
                          </Form.Item>
                          <Form.Item {...layout} label="名称">
                            <Input
                              style={{ width: 300 }}
                              value={currentName}
                              onChange={this.changeCurrentName}
                              placeholder="请输入科目名称"
                            />
                          </Form.Item>
                          <Form.Item {...layout} label="类别">
                            <Radio.Group onChange={this.changeCurrentIsSw} value={currentIs_sw}>
                              <Radio value={2}>特种设备</Radio>
                              <Radio value={1}>特种作业</Radio>
                            </Radio.Group>
                          </Form.Item>
                          <Form.Item label="排序" {...layout}>
                            <InputNumber
                              style={{ width: 300 }}
                              value={currentNum}
                              onChange={this.changeCurrentNum}
                              placeholder="请输入科目排序"
                            />
                          </Form.Item>
                          <Form.Item {...tailLayout}>
                            <Authorized authority={[203]}>
                              <Button type="primary" onClick={this.submitEdit}>
                                修改
                          </Button>
                            </Authorized>
                            <Authorized authority={[204]}>
                              <Button style={{ marginLeft: 20 }} danger onClick={this.deleteHandle}>
                                删除
                          </Button>
                            </Authorized>

                          </Form.Item>
                        </Form>
                      </Spin>
                    </Tabs.TabPane>
                  </React.Fragment>
                )}
              </Tabs>
            </Col>
          </Row>
        </Card>
      </PageContainer>
    );
  }
}

export default Index;
